package com.fancy.learncenter.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fancy.learncenter.adapter.ReleaseWDPIcAdapter;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.PermissionUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.CustomProgressDialog;
import com.fancy.learncenter.view.LiZhiDialog;
import com.fancy.learncenter.view.PopupWindowCutPic;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReleaseWenDaActivity extends TakePhotoActivity {

    private static final int ACCESS_LOCATION_RESULT_CODE = 100111;

    @Bind(R.id.next)
    TextView next;
    @Bind(R.id.et_title)
    EditText etTitle;
    @Bind(R.id.yibaocun)
    TextView yibaocun;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.ll)
    LinearLayout ll;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.et_content)
    EditText etContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_wenda);
        ButterKnife.bind(this);
        title.setText("发布问答");
        next.setText("完成");
        takePhoto = getTakePhoto();
        takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);

        initRecycleView();
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
//        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
//
//        builder.setWithOwnGallery(true);
//
//        builder.setCorrectImage(true);
////        if (rgPickTool.getCheckedRadioButtonId() == R.id.rbPickWithOwn) {
////
////        }
////        if (rgCorrectTool.getCheckedRadioButtonId() == R.id.rbCorrectYes) {
////
////        }
//        takePhoto.setTakePhotoOptions(builder.create());

    }

    ReleaseWDPIcAdapter releaseWDPIcAdapter;

    private void initRecycleView() {
        ArrayList itemData = new ArrayList();
        itemData.add("res://com.superservice.lya/" + R.mipmap.ic_tianjia);


        releaseWDPIcAdapter = new ReleaseWDPIcAdapter(this, itemData);
        releaseWDPIcAdapter.setCallBack(new ReleaseWDPIcAdapter.CallBack() {
            @Override
            public void OnClick() {


                if (popupWindowCutPic == null) {
                    popupWindowCutPic = new PopupWindowCutPic(recycleView);
                    popupWindowCutPic.setOnClickListener(new PopupWindowCutPic.CutPicCallBack() {
                        @Override
                        public void choose() {
//                            takePhoto.onPickFromGallery();
                            takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);

                            takePhoto.onPickMultiple(6);
                        }

                        @Override
                        public void cancel() {

                        }

                        @Override
                        public void camera() {
                            takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);
                            takePhoto.onPickFromCaptureWithCrop(Utils.getCutPicPath(), Utils.getCutPicCropOptions());
                        }

                        @Override
                        public void see() {

                        }
                    });

                }

                popupWindowCutPic.isShow();
//                Uri imageUri = Uri.fromFile(Utils.getLiZiPicFile());
//                takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
            }
        });

        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 3);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);

        recycleView.setAdapter(releaseWDPIcAdapter);
    }

    PopupWindowCutPic popupWindowCutPic;
    TakePhoto takePhoto;

    @OnClick({R.id.back, R.id.next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
//                LiZhiDialog.show(this, R.mipmap.bg_tuxing, "退出前，您需要保存吗？",
//                        true, "不保存", "保存", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                finish();
//                                LiZhiDialog.dismissDialog();
//                            }
//                        }, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                finish();
//                                LiZhiDialog.dismissDialog();
//                            }
//                        });
                break;
            case R.id.next:

                if (TextUtils.isEmpty(etTitle.getText())) {
                    ToastUtil.show("请输入标题");
                    return;
                }

                if (TextUtils.isEmpty(etContent.getText())) {
                    ToastUtil.show("请输入内容");
                    return;
                }
                submit();

                break;
            case R.id.delete:
//                imageTemp.setVisibility(View.GONE);
                break;
        }
    }


    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                    //权限被允许（如果被拒绝的话就会提示去设置中打开权限）
                    startActivityForResult(new Intent(ReleaseWenDaActivity.this, MapLocationActivity.class), ACCESS_LOCATION_RESULT_CODE);
                    break;
            }
        }
    };

    /**
     * 定位权限授权回调
     */
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }


    private CropOptions getCropOptions() {

        CropOptions.Builder builder = new CropOptions.Builder();
//        builder.setWithOwnCrop(false);
        return builder.create();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        if (result.getImages() != null && !TextUtils.isEmpty(result.getImage().getCompressPath())) {

            ArrayList<TImage> images = result.getImages();

            for (int i = 0; i < images.size(); i++) {
//                picData.add(images.get(i).getCompressPath());

                releaseWDPIcAdapter.itemDatas.add(releaseWDPIcAdapter.itemDatas.size() - 1, images.get(i).getCompressPath());

            }
        }

//        if (result.getImage() != null && !TextUtils.isEmpty(result.getImage().getCompressPath())) {
//            picData.add(result.getImage().getCompressPath());
//        }


//
//        itemDatas.addAll(picData);
//

        releaseWDPIcAdapter.notifyDataSetChanged();
    }


    Dialog dialog;
    boolean isSubmit = false;

    private void disDia() {

        isSubmit = false;
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    private void submit() {

        if (isSubmit) {
            return;
        } else {
            isSubmit = true;
            if (dialog == null) {
                dialog = CustomProgressDialog.creatRequestDialog(this);
            }
            dialog.show();

        }


        if (TextUtils.isEmpty(etTitle.getText().toString())) {
            ToastUtil.show("标题不能为空");
            return;
        }
        if (TextUtils.isEmpty(etContent.getText().toString())) {
            ToastUtil.show("内容不能为空");
            return;
        }
        Map maps = new HashMap();

        List<String> datas = new ArrayList();
//        for (int i = 0; i < picData.size(); i++) {
//            datas.add("data:image/jpeg;base64," + Utils.imageToBase64(picData.get(i)));
//        }


        for (int i = 0; i < releaseWDPIcAdapter.itemDatas.size() - 1; i++) {
//            if (!releaseWDPIcAdapter.itemDatas.get(i).contains("com.superservice.lya")) {
//
//            }
            datas.add("data:image/jpeg;base64," + Utils.imageToBase64(releaseWDPIcAdapter.itemDatas.get(i)));
        }


        maps.put("title", etTitle.getText().toString());

        maps.put("content", etContent.getText().toString());

        String[] array = datas.toArray(new String[0]);


        HttpMehtod.getInstance().releaseWd2(maps, array, new IdeaObserver<BaseDataBean>() {

            @Override
            public void onSuccess(BaseDataBean stringBaseDataBean) {
                ToastUtil.show("发布成功");
                disDia();
                finish();
            }

            @Override
            public void onFail(int errorCode) {
                disDia();
            }

        });

    }
}
